package com.example.exceptiondemo.entity;

import com.alibaba.fastjson.JSON;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一返回实体
 *
 * @author YXC
 * @copyright (C), 2019-2021, 河北地质大学
 * @filename R
 * @date 2021/4/25 15:32
 * @history <author>     <time>      <version>       <desc>
 * 作者名       修改时间       版本号           描述
 **/
public class R extends HashMap<String, Object> {

    public static Integer SUCCESS = 200;
    public static Integer ERROR = 400;

    public R() {
        put("status", SUCCESS);
        put("message", "success");
        put("timestamp", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }

    public static R error(int status, String message) {
        R r = new R();
        r.put("status", status);
        r.put("message", message);
        return r;
    }

    public static R error() {
        return error(ERROR, "内部服务器错误，执行失败");
    }

    public static R error(String message) {
        return error(ERROR, message);
    }



    public static R error(int status, String message, String path) {
        R r = new R();
        r.put("status", status);
        r.put("message", message);
        r.put("path", path);
        return r;
    }

    public static R ok(String message) {
        R r = new R();
        r.put("message", message);
        return r;
    }

    public static R ok(String message, Object data) {
        R r = new R();
        r.put("message", message);
        r.put("data", data);
        return r;
    }

    public static R ok(Object data) {
        return R.ok().put("data", data);
    }

    public static R ok(List data) {
        return R.array(data);
    }
    
    public static R array(List arr) {
        return R.ok().put("data", arr);
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public String toJSONString() {
        return JSON.toJSONString(this);
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public int getStauts() {
        return (int) super.get("status");
    }

    public String getmessage() {
        return (String) super.get("message");
    }

}
